<?php

namespace App\utils;

/**
 * rsa加密与解密工具
 * User: 姚鸿杰
 * Date: 2019/4/10
 * Time: 21:10
 */
class RsaUtils
{
    private static function getPrivateKey($privateKey)
    {
        return openssl_pkey_get_private($privateKey);
    }

    private static function getPublicKey($publicKey)
    {
        return openssl_pkey_get_public($publicKey);
    }

    private static function openPublicKey()
    {
        return openssl_pkey_get_public(file_get_contents(base_path('keys/rsa_public_key.pem')));
    }

    private static function openPrivateKey()
    {
        return openssl_pkey_get_private(file_get_contents(base_path('keys/rsa_private_key.pem')));
    }

    /**
     * 私钥加密
     */
    public static function privateEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        $privateKey = RsaUtils::openPrivateKey();
        openssl_private_encrypt($data, $encrypted, self::getPrivateKey($privateKey));
        openssl_free_key($privateKey);
        return $encrypted ? base64_encode($encrypted) : null;
    }

    /**
     * 私钥解密
     */
    public static function privateDecrypt($encrypted)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        $privateKey = RsaUtils::openPrivateKey();
        openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::getPrivateKey($privateKey));
        openssl_free_key($privateKey);
        return $decrypted ?: null;
    }

    /**
     * 公私加密
     */
    public static function publicEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        $publicKey = RsaUtils::openPublicKey();
        openssl_public_encrypt($data, $encrypted, self::getPublicKey($publicKey));
        openssl_free_key($publicKey);
        return $encrypted ? base64_encode($encrypted) : null;
    }

    /**
     * 公私解密
     */
    public static function publicDecrypt($encrypted)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        $publicKey = RsaUtils::openPublicKey();
        openssl_public_decrypt(base64_decode($encrypted), $decrypted, self::getPublicKey($publicKey));
        openssl_free_key($publicKey);
        return $decrypted ?: null;
    }

    /**
     * 密钥签名
     */
    public static function setSign($data)
    {
        $privateKey = RsaUtils::openPrivateKey();
        openssl_sign($data, $signature, $privateKey);
        openssl_free_key($privateKey);
        return base64_encode($signature);
    }

    /**
     * 公私解签
     */
    public static function untieSign($toSign, $sign)
    {
        $publicKey = RsaUtils::openPublicKey();
        $result = openssl_verify($toSign, base64_decode($sign), $publicKey);
        openssl_free_key($publicKey);
        return $result;
    }
}